use std::os::raw::{c_int, c_char};
use std::ptr;

use ratatui::style::{Color, Style, Modifier};
use crate::{RatatuiResult, c_str_to_string};

/// 扩展的颜色枚举，支持更多颜色
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RatatuiColorAdvanced {
    // 基础颜色
    Reset = 0,
    Black = 1,
    Red = 2,
    Green = 3,
    Yellow = 4,
    Blue = 5,
    Magenta = 6,
    Cyan = 7,
    Gray = 8,
    DarkGray = 9,
    LightRed = 10,
    LightGreen = 11,
    LightYellow = 12,
    LightBlue = 13,
    LightMagenta = 14,
    LightCyan = 15,
    White = 16,
    
    // 256色支持
    Indexed = 17,
    
    // RGB颜色支持
    Rgb = 18,
}

/// RGB颜色结构
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct RatatuiRgbColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

/// 扩展的修饰符枚举
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RatatuiModifierAdvanced {
    Bold = 1,
    Dim = 2,
    Italic = 4,
    Underlined = 8,
    SlowBlink = 16,
    RapidBlink = 32,
    Reversed = 64,
    CrossedOut = 128,
    Hidden = 256,
}

/// 高级主题结构
#[repr(C)]
#[derive(Debug, Clone)]
pub struct RatatuiThemeAdvanced {
    pub primary_color: RatatuiColorAdvanced,
    pub secondary_color: RatatuiColorAdvanced,
    pub background_color: RatatuiColorAdvanced,
    pub text_color: RatatuiColorAdvanced,
    pub accent_color: RatatuiColorAdvanced,
    pub error_color: RatatuiColorAdvanced,
    pub warning_color: RatatuiColorAdvanced,
    pub success_color: RatatuiColorAdvanced,
}

impl RatatuiColorAdvanced {
    /// 转换为Ratatui颜色
    pub fn to_ratatui_color(&self, rgb: Option<RatatuiRgbColor>, index: Option<u8>) -> Color {
        match self {
            RatatuiColorAdvanced::Reset => Color::Reset,
            RatatuiColorAdvanced::Black => Color::Black,
            RatatuiColorAdvanced::Red => Color::Red,
            RatatuiColorAdvanced::Green => Color::Green,
            RatatuiColorAdvanced::Yellow => Color::Yellow,
            RatatuiColorAdvanced::Blue => Color::Blue,
            RatatuiColorAdvanced::Magenta => Color::Magenta,
            RatatuiColorAdvanced::Cyan => Color::Cyan,
            RatatuiColorAdvanced::Gray => Color::Gray,
            RatatuiColorAdvanced::DarkGray => Color::DarkGray,
            RatatuiColorAdvanced::LightRed => Color::LightRed,
            RatatuiColorAdvanced::LightGreen => Color::LightGreen,
            RatatuiColorAdvanced::LightYellow => Color::LightYellow,
            RatatuiColorAdvanced::LightBlue => Color::LightBlue,
            RatatuiColorAdvanced::LightMagenta => Color::LightMagenta,
            RatatuiColorAdvanced::LightCyan => Color::LightCyan,
            RatatuiColorAdvanced::White => Color::White,
            RatatuiColorAdvanced::Indexed => {
                if let Some(idx) = index {
                    Color::Indexed(idx)
                } else {
                    Color::White // 默认值
                }
            }
            RatatuiColorAdvanced::Rgb => {
                if let Some(rgb_color) = rgb {
                    Color::Rgb(rgb_color.r, rgb_color.g, rgb_color.b)
                } else {
                    Color::White // 默认值
                }
            }
        }
    }
}

impl RatatuiModifierAdvanced {
    /// 转换为Ratatui修饰符
    pub fn to_ratatui_modifier(&self) -> Modifier {
        match self {
            RatatuiModifierAdvanced::Bold => Modifier::BOLD,
            RatatuiModifierAdvanced::Dim => Modifier::DIM,
            RatatuiModifierAdvanced::Italic => Modifier::ITALIC,
            RatatuiModifierAdvanced::Underlined => Modifier::UNDERLINED,
            RatatuiModifierAdvanced::SlowBlink => Modifier::SLOW_BLINK,
            RatatuiModifierAdvanced::RapidBlink => Modifier::RAPID_BLINK,
            RatatuiModifierAdvanced::Reversed => Modifier::REVERSED,
            RatatuiModifierAdvanced::CrossedOut => Modifier::CROSSED_OUT,
            RatatuiModifierAdvanced::Hidden => Modifier::HIDDEN,
        }
    }
}

/// 预定义主题
impl RatatuiThemeAdvanced {
    /// 默认主题
    pub fn default() -> Self {
        RatatuiThemeAdvanced {
            primary_color: RatatuiColorAdvanced::Blue,
            secondary_color: RatatuiColorAdvanced::Cyan,
            background_color: RatatuiColorAdvanced::Black,
            text_color: RatatuiColorAdvanced::White,
            accent_color: RatatuiColorAdvanced::Yellow,
            error_color: RatatuiColorAdvanced::Red,
            warning_color: RatatuiColorAdvanced::Yellow,
            success_color: RatatuiColorAdvanced::Green,
        }
    }
    
    /// 暗色主题
    pub fn dark() -> Self {
        RatatuiThemeAdvanced {
            primary_color: RatatuiColorAdvanced::LightBlue,
            secondary_color: RatatuiColorAdvanced::LightCyan,
            background_color: RatatuiColorAdvanced::Black,
            text_color: RatatuiColorAdvanced::Gray,
            accent_color: RatatuiColorAdvanced::LightYellow,
            error_color: RatatuiColorAdvanced::LightRed,
            warning_color: RatatuiColorAdvanced::LightYellow,
            success_color: RatatuiColorAdvanced::LightGreen,
        }
    }
    
    /// 亮色主题
    pub fn light() -> Self {
        RatatuiThemeAdvanced {
            primary_color: RatatuiColorAdvanced::Blue,
            secondary_color: RatatuiColorAdvanced::Cyan,
            background_color: RatatuiColorAdvanced::White,
            text_color: RatatuiColorAdvanced::Black,
            accent_color: RatatuiColorAdvanced::Yellow,
            error_color: RatatuiColorAdvanced::Red,
            warning_color: RatatuiColorAdvanced::Yellow,
            success_color: RatatuiColorAdvanced::Green,
        }
    }
    
    /// 霓虹主题
    pub fn neon() -> Self {
        RatatuiThemeAdvanced {
            primary_color: RatatuiColorAdvanced::LightMagenta,
            secondary_color: RatatuiColorAdvanced::LightCyan,
            background_color: RatatuiColorAdvanced::Black,
            text_color: RatatuiColorAdvanced::LightGreen,
            accent_color: RatatuiColorAdvanced::LightYellow,
            error_color: RatatuiColorAdvanced::LightRed,
            warning_color: RatatuiColorAdvanced::Yellow,
            success_color: RatatuiColorAdvanced::LightGreen,
        }
    }
}

/// 创建RGB颜色
#[no_mangle]
pub extern "C" fn ratatui_rgb_color_new(r: u8, g: u8, b: u8) -> *mut RatatuiRgbColor {
    let rgb_color = RatatuiRgbColor { r, g, b };
    Box::into_raw(Box::new(rgb_color))
}

/// 释放RGB颜色
#[no_mangle]
pub extern "C" fn ratatui_rgb_color_free(rgb_color: *mut RatatuiRgbColor) {
    if !rgb_color.is_null() {
        unsafe {
            let _ = Box::from_raw(rgb_color);
        }
    }
}

/// 创建高级样式
#[no_mangle]
pub extern "C" fn ratatui_style_advanced_new() -> *mut Style {
    let style = Style::default();
    Box::into_raw(Box::new(style))
}

/// 设置前景色（高级版本）
#[no_mangle]
pub extern "C" fn ratatui_style_set_fg_advanced(
    style: *mut Style,
    color: RatatuiColorAdvanced,
    rgb: *const RatatuiRgbColor,
    index: u8,
) -> c_int {
    if style.is_null() {
        return RatatuiResult::ErrorNullPointer as c_int;
    }

    unsafe {
        let style_ref = &mut *style;
        let rgb_color = if !rgb.is_null() {
            Some(*rgb)
        } else {
            None
        };
        let index_option = if color == RatatuiColorAdvanced::Indexed {
            Some(index)
        } else {
            None
        };
        
        let ratatui_color = color.to_ratatui_color(rgb_color, index_option);
        *style_ref = style_ref.fg(ratatui_color);
        RatatuiResult::Ok as c_int
    }
}

/// 设置背景色（高级版本）
#[no_mangle]
pub extern "C" fn ratatui_style_set_bg_advanced(
    style: *mut Style,
    color: RatatuiColorAdvanced,
    rgb: *const RatatuiRgbColor,
    index: u8,
) -> c_int {
    if style.is_null() {
        return RatatuiResult::ErrorNullPointer as c_int;
    }

    unsafe {
        let style_ref = &mut *style;
        let rgb_color = if !rgb.is_null() {
            Some(*rgb)
        } else {
            None
        };
        let index_option = if color == RatatuiColorAdvanced::Indexed {
            Some(index)
        } else {
            None
        };
        
        let ratatui_color = color.to_ratatui_color(rgb_color, index_option);
        *style_ref = style_ref.bg(ratatui_color);
        RatatuiResult::Ok as c_int
    }
}

/// 添加修饰符（高级版本）
#[no_mangle]
pub extern "C" fn ratatui_style_add_modifier_advanced(
    style: *mut Style,
    modifier: RatatuiModifierAdvanced,
) -> c_int {
    if style.is_null() {
        return RatatuiResult::ErrorNullPointer as c_int;
    }

    unsafe {
        let style_ref = &mut *style;
        let ratatui_modifier = modifier.to_ratatui_modifier();
        *style_ref = style_ref.add_modifier(ratatui_modifier);
        RatatuiResult::Ok as c_int
    }
}

/// 创建高级主题
#[no_mangle]
pub extern "C" fn ratatui_theme_advanced_new(theme_type: c_int) -> *mut RatatuiThemeAdvanced {
    let theme = match theme_type {
        0 => RatatuiThemeAdvanced::default(),
        1 => RatatuiThemeAdvanced::dark(),
        2 => RatatuiThemeAdvanced::light(),
        3 => RatatuiThemeAdvanced::neon(),
        _ => RatatuiThemeAdvanced::default(),
    };
    Box::into_raw(Box::new(theme))
}

/// 释放高级主题
#[no_mangle]
pub extern "C" fn ratatui_theme_advanced_free(theme: *mut RatatuiThemeAdvanced) {
    if !theme.is_null() {
        unsafe {
            let _ = Box::from_raw(theme);
        }
    }
}

/// 从高级主题获取颜色
#[no_mangle]
pub extern "C" fn ratatui_theme_advanced_get_color(
    theme: *const RatatuiThemeAdvanced,
    color_type: c_int,
) -> RatatuiColorAdvanced {
    if theme.is_null() {
        return RatatuiColorAdvanced::White;
    }

    unsafe {
        let theme_ref = &*theme;
        match color_type {
            0 => theme_ref.primary_color,
            1 => theme_ref.secondary_color,
            2 => theme_ref.background_color,
            3 => theme_ref.text_color,
            4 => theme_ref.accent_color,
            5 => theme_ref.error_color,
            6 => theme_ref.warning_color,
            7 => theme_ref.success_color,
            _ => RatatuiColorAdvanced::White,
        }
    }
}
